package com

import (
	"beergo/app/sys/models"
	"beergo/conf/const/code"
	"beergo/lib/base/controller"
	"beergo/lib/event"
	"beergo/lib/tool"
	"beergo/plugins/ali"
	"encoding/base64"
	"fmt"
	"github.com/beego/beego/v2/server/web"
	"time"
)

type SmsController struct {
	controller.ContainerController
}

func init() {
	web.Router("/sms",&SmsController{},"*:SmsSendAction")
	web.Router("/sms_login",&SmsController{},"*:SmsLoginAction")
	web.Router("/sms_password",&SmsController{},"*:SmsChangePasswordAction")
}

func (this *SmsController) SmsSendAction() {
	phone := this.GetParamString("phone")
	smsCode := tool.CreateRand(4)
	err:=this.SetCache("sms_code",smsCode)
	this.AnaliseErrors(err)
	err = ali.Send(phone,smsCode)
	this.AnaliseErrors(err)
	this.ReturnSuccess("虚拟验证码 ","")
}

func (this *SmsController) SmsLoginAction() {
	var data = &struct {
		Phone string `json:"phone"`
		Code string `json:"code"`
	}{}

	err:=this.FillModel(data)
	if err != nil {
		this.AnaliseErrors(err)
	}
	smsCode ,err := this.GetCacheString("sms_code")
	if err != nil {
		this.StopError(code.Error,"验证码过期","")
	}
	if data.Code != smsCode {
		this.StopError(code.Error,"验证码有误",smsCode)
	}
	rep:=models.UserRepository{}
	find := rep.FindOneBy(tool.M{"phone":data.Phone},nil)
	if find.Id == 0 {
		this.StopError(code.Error,"账号不存在","")
	}

	vi:=web.AppConfig.DefaultString("vi","123456")
	token := tool.AesEncrypt(fmt.Sprintf("user %d vi %d",find.Id,time.Now().Unix()),vi)
	tk:=base64.StdEncoding.EncodeToString([]byte(token))
	println(tk)
	find.Token = tk
	_,err=find.Save()
	if err != nil {
		this.AnaliseErrors(err)
	}

	//find标识账号信息，
	this.JsonData["account"] = find
	//发出登录事件，需要处理的监听器在JsonData中添加个系统的返回
	event.DispatchToMany("Login", this.JsonData,this.Ctx)
	//this.JsonData["account"] =  user
	this.ReturnSuccess("登录成功", this.JsonData)
}
func (this *SmsController) SmsChangePasswordAction() {
	var data = &struct {
		Phone string `json:"phone"`
		Code string `json:"code"`
		Password string `json:"password"`
	}{}

	err:=this.FillModel(data)
	if err != nil {
		this.AnaliseErrors(err)
	}
	smsCode ,err := this.GetCacheString("sms_code")
	if err != nil {
		this.StopError(code.Error,"验证码过期","")
	}
	if data.Code != smsCode {
		this.StopError(code.Error,"验证码有误",smsCode)
	}
	rep:=models.UserRepository{}
	find := rep.FindOneBy(tool.M{"phone":data.Phone},nil)
	if find.Id == 0 {
		this.StopError(code.Error,"账号不存在","")
	}

	vi:=web.AppConfig.DefaultString("vi","123456")
	token := tool.AesEncrypt(fmt.Sprintf("user %d vi %d",find.Id,time.Now().Unix()),vi)
	tk:=base64.StdEncoding.EncodeToString([]byte(token))
	println(tk)
	find.Token = tk
	find.Password = data.Password
	_,err=find.Save()
	if err != nil {
		this.AnaliseErrors(err)
	}

	//find标识账号信息，
	this.JsonData["account"] = find
	//发出登录事件，需要处理的监听器在JsonData中添加个系统的返回
	event.DispatchToMany("Login", this.JsonData,this.Ctx)
	this.ReturnSuccess("登录成功", this.JsonData)
}